package controllers

import (
	data "HomeStation/controllers"
	user "HomeStation/db"
	utils "HomeStation/utils"
	"fmt"

	"github.com/astaxie/beego/orm"
	"github.com/beego/beego/v2/server/web"
)

type UserControlles struct {
	web.Controller
}

///登录功能
func (this *UserControlles) Login() {
	var err error
	var response data.Response

	err = utils.CheckRequestParams(&this.Controller, "name", "password")
	if nil != err {
		response = data.Response{Code: 304, Message: fmt.Sprintf("登录失败: 请输入: %v", err)}
		this.Data["json"] = &response
		this.ServeJSON()
		return
	}

	name := this.GetString("name")
	password := this.GetString("password")
	us := user.User{Name: name}

	o := orm.NewOrm()
	err = o.Read(&us, "Name")
	if err != nil {
		response = data.Response{Code: 304, Message: fmt.Sprintf("登录失败: 找不到用户: %v", name)}
		this.Data["json"] = &response
		this.ServeJSON()
		return
	}

	if us.Password != password {
		response = data.Response{Code: 304, Message: "登录失败: 密码错误:"}
		this.Data["json"] = &response
		this.ServeJSON()
		return
	}

	us.Password = ""
	data.SetSession(&this.Controller, us.Id)
	response = data.Response{Code: 200, Message: "登录成功", Data: us}
	this.Data["json"] = &response
	this.ServeJSON()
}

///用户注册接口
func (this *UserControlles) Register() {
	var err error
	var response data.Response
	err = utils.CheckRequestParams(&this.Controller, "name", "password", "nickName")
	if nil != err {
		response = data.Response{Code: 0, Message: fmt.Sprintf("注册失败 %v", err)}
		this.Data["json"] = &response
		this.ServeJSON()
	}
	name := this.GetString("name")
	password := this.GetString("password")
	nickName := this.GetString("nickName")

	user := user.User{Name: name, Password: password, NickName: nickName}
	o := orm.NewOrm()
	err = o.Read(&user, "Name")
	if nil == err {
		response = data.Response{Code: 0, Message: "注册失败 已存在相同用户"}
	} else {
		_, err = o.Insert(&user)
		if nil == err {
			data.SetSession(&this.Controller, user.Id)
			response = data.Response{Code: 200, Message: "注册成功"}
		} else {
			response = data.Response{Code: 0, Message: fmt.Sprintf("注册失败 %v", err)}
		}
	}
	this.Data["json"] = &response
	this.ServeJSON()

}
